package com.eol.service.content;

import com.eol.entity.dto.CourseTypeDto;
import com.eol.entity.dto.MerchantDto;
import com.eol.entity.po.content.ZCourseType;
import com.eol.entity.po.merchant.ZMerchant;
import com.eol.mapper.business.content.ZCourseTypeMapper;
import com.eol.mapper.config.tkMybatis.MybatisBaseService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 课程分类表
 *
 * @author liulinhui
 * @email 1249055292@qq.com
 * @date 2020-06-09 10:53:15
 */
@Service
public class ZCourseTypeService extends MybatisBaseService<ZCourseTypeMapper, ZCourseType> {

    public List<CourseTypeDto> selectCourseList(ZCourseType zCourseType) {
        return mapper.selectCourseList(zCourseType);
    }

    public Object buildTree(List<CourseTypeDto> list) {
        Set<CourseTypeDto> trees = new LinkedHashSet<>();
        Set<CourseTypeDto> depts = new LinkedHashSet<>();
        List<String> deptNames = list.stream().map(CourseTypeDto::getName).collect(Collectors.toList());
        boolean isChild;
        for (CourseTypeDto courseTypeDto : list) {
            isChild = false;
            if (StringUtils.isEmpty(courseTypeDto.getPid())) {
                trees.add(courseTypeDto);
            }
            for (CourseTypeDto it : list) {
                if (it.getPid().equals(courseTypeDto.getId())) {
                    isChild = true;
                    if (courseTypeDto.getChildren() == null) {
                        courseTypeDto.setChildren(new ArrayList<>());
                    }
                    courseTypeDto.getChildren().add(it);
                }
            }
            if (isChild)
                depts.add(courseTypeDto);
            else if (!deptNames.contains(this.selectById(courseTypeDto.getId()).getName()))
                depts.add(courseTypeDto);
        }

        if (CollectionUtils.isEmpty(trees)) {
            trees = depts;
        }

        Integer totalElements = list.size();

        Map<String, Object> map = new HashMap<>();
        map.put("totalElements", totalElements);
        map.put("content", CollectionUtils.isEmpty(trees) ? list : trees);
        return map;
    }
}